
const Service = require('egg').Service;
const { USER_TICKET, USER_TOKEN, TICKET_USER_ID, TOKEN_USER_ID, USER_DATA } = require('../constant/redis');
const uuidv1 = require('uuid/v1');

class PublicService extends Service {
    async getAccessToken() {
        const ctx = this.ctx;
        return new Promise(async (resolve, reject) => {
            // const id = 'system_access_token';
            // const id = ctx.app.mongoose.Types.ObjectId();
            const id = '1f6ad2a0-d3d5-11e9-8fe8-db182b57b855'
            try {
                // 使用默认角色
                let role = ctx.app.constant.DEFAULT_ROLE;
                let ticket = await ctx.service.cache.get([USER_TICKET, id]);
                let token = await ctx.service.cache.get([USER_TOKEN, id]);
                if (!token) {
                    // 使用config里面的secret签发一个Token，包含了用户的ID和角色，并且设置了有效时间
                    token = ctx.app.jwt.sign({
                        id,
                        role
                    }, ctx.app.config.jwt.secret, {
                            expiresIn: ctx.app.config.jwt.expiresIn
                        }
                    );
                    await ctx.service.cache.set([TOKEN_USER_ID, token], id, ctx.app.constant.ACCESS_TOKEN_EX * 60 * 60);
                    ticket = uuidv1();
                    await ctx.service.cache.set([TICKET_USER_ID, ticket], id, ctx.app.constant.ACCESS_TOKEN_EX * 60 * 60);
                    await ctx.service.cache.set([USER_DATA, id], {}, ctx.app.constant.ACCESS_TOKEN_EX * 60 * 60);
                    await ctx.service.cache.set([USER_TOKEN, id], token, ctx.app.constant.ACCESS_TOKEN_EX * 60 * 60);
                    await ctx.service.cache.set([USER_TICKET, id], ticket, ctx.app.constant.ACCESS_TOKEN_EX * 60 * 60);
                }
                resolve(ticket)
            }
            catch (err) {
                reject(err)
            }
        })
    }
}

module.exports = PublicService;
